import { DatabaseProvider } from "@/lib/db";

let _instance: CartService;

class CartService {
  private db: DatabaseProvider;

  constructor(db: DatabaseProvider) {
    this.db = db;
  }

  // 获取单例实例
  static getInstance(db: DatabaseProvider) {
    if (!_instance) {
      _instance = new CartService(db);
    }
    return _instance;
  }

  // 添加商品到购物车
  async addToCart(userId: string, productId: string, quantity: number) {
    return await this.db.database.insert({
      user_id: userId,
      product_id: productId,
      quantity
    }).into('cart');
  }

  // 更新购物车商品数量
  async updateCart(userId: string, productId: string, quantity: number) {
    return await this.db.database('cart')
      .where({ user_id: userId, product_id: productId })
      .update({ quantity, updated_at: new Date() });
  }

  // 清空购物车
  async clearCart(userId: string) {
    return await this.db.database('cart')
      .where({ user_id: userId })
      .delete();
  }

  // 获取用户购物车内容
  async getCart(userId: string) {
    return await this.db.database.select().from('cart')
      .where({ user_id: userId });
  }
}

export default CartService;
